package com.rinlink.gateway.jt808.controller;

import com.google.common.collect.Maps;
import com.rinlink.gateway.jt808.common.CommonResult;
import com.rinlink.gateway.jt808.common.CommonStatusCode;
import com.rinlink.gateway.jt808.exception.HttpApiException;
import com.rinlink.gateway.jt808.jt808.BytesRespMsgBody;
import com.rinlink.gateway.jt808.jt808.CustomMsgType;
import com.rinlink.gateway.jt808.model.Base64Jt808ResponseInDTO;
import com.rinlink.gateway.jt808.service.WebHookService;
import io.github.hylexus.jt.exception.JtCommunicationException;
import io.github.hylexus.jt.exception.JtSessionNotFoundException;
import io.github.hylexus.jt808.dispatcher.CommandSender;
import io.github.hylexus.jt808.msg.resp.CommandMsg;
import io.github.hylexus.jt808.session.Jt808SessionManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.io.IOException;
import java.util.Base64;
import java.util.List;

@RestController
@RequestMapping("/terminals")
public class TerminalsController {

    @Autowired
    Jt808SessionManager jt808SessionManager;

    @Autowired
    CommandSender commandSender;

    @Autowired
    WebHookService webHookService;


    @GetMapping
    public List getList(int page,int pageSize){
        return jt808SessionManager.list(page,pageSize);
    }

    @PostMapping("/{terminalId}/response/base64")
    public CommonResult send(@PathVariable String terminalId,
                             @RequestBody @Valid Base64Jt808ResponseInDTO inDTO) throws IOException, InterruptedException, HttpApiException {
        byte[] bytes = null;
        try {
            bytes = Base64.getDecoder().decode(inDTO.getBody() == null ? "" : inDTO.getBody());
        }catch (Exception e){
            throw new HttpApiException(HttpStatus.BAD_REQUEST,CommonStatusCode.INVALID_PARAM,"body 参数格式错误");
        }
        CommandMsg msg = CommandMsg.of(
                terminalId,
                new CustomMsgType(inDTO.getMsgId()),
                new BytesRespMsgBody(inDTO.getMsgId(),bytes)
        );
        try {
            commandSender.sendCommand(msg);
        }catch (JtCommunicationException e){
            throw new HttpApiException(HttpStatus.INTERNAL_SERVER_ERROR,CommonStatusCode.UNKNOWN_ERROR,"未知异常");
        }catch (JtSessionNotFoundException e){
            throw new HttpApiException(HttpStatus.NOT_FOUND,CommonStatusCode.TERMINAL_OFFLINE,"设备不在线");
        }
        return CommonResult.success(Maps.newHashMap());
    }


}
